package cz.muni.fi.pa165.hauntedhouses.rest.web;

import cz.muni.fi.pa165.hauntedhouses.dto.AbilityDTO;
import cz.muni.fi.pa165.hauntedhouses.dto.AbilityType;
import cz.muni.fi.pa165.hauntedhouses.dto.GhostDTO;
import cz.muni.fi.pa165.hauntedhouses.dto.HouseDTO;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

/**
 * An action bean for manipulation with ghost entity via REST api
 * 
 * @author Jarda Benda
 */
@UrlBinding("/jsp/ghosts")
public class GhostsActionBean implements ActionBean {
    final static String URI="http://localhost:8080/pa165/rest";
    private ActionBeanContext context;
    
    @SpringBean
    RestTemplate restTemplate;

    public HttpHeaders getHttpHeader(){
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Authorization", "Basic rest:rest");
        return requestHeaders;
    }
    
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }   
    
    @DefaultHandler
    public Resolution ghosts() {
        return new ForwardResolution("/jsp/ghosts.jsp");
    }
    public List<GhostDTO> getGhosts() {
        GhostDTO[] ghosts = restTemplate.getForObject(URI+"/ghosts", GhostDTO[].class);
//        ResponseEntity<GhostDTO[]> ghosts = restTemplate.exchange(URI+"/ghosts", HttpMethod.POST, new HttpEntity<GhostDTO[]>(getHttpHeader()), GhostDTO[].class);
        return (Arrays.asList(ghosts));
    }
 
    public List<HouseDTO> getHouses() {
        HouseDTO[] houses = restTemplate.getForObject(URI+"/houses", HouseDTO[].class);
        return (Arrays.asList(houses));
    }
    
    public List<AbilityDTO> getAbilities() {
        List<AbilityDTO> abilities = new ArrayList<AbilityDTO>();
        List<AbilityDTO> abilitiesByType = new ArrayList<AbilityDTO>();
        int lvl = ghost.getLvl();
        
        AbilityDTO[] ablts = restTemplate.getForObject(URI+"/abilitiesByType?type="+ghost.getAbilityType(), AbilityDTO[].class);
        for(AbilityDTO a : ablts) {
            abilitiesByType.add(a);
        }
        
        for(AbilityDTO a : ghost.getAbilities()) {
            abilitiesByType.remove(a);
        }
        
        for(AbilityDTO a : abilitiesByType) {
            if(lvl <= 2) {
                if(a.getAbilityLevel() == 1) {
                    abilities.add(a);
                }
            } else if(lvl <= 5) {
                if(a.getAbilityLevel() <= 2) {
                    abilities.add(a);
                }
            } else if(lvl <= 6){
                if(a.getAbilityLevel() <= 3) {
                    abilities.add(a);
                }
            }
        }
        return abilities;
    }
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"add", "save"}, field = "name", required = true),
            @Validate(on = {"add", "save"}, field = "abilityType", required = true),
            @Validate(on = {"add", "save"}, field = "description", required = true)
    })
    private GhostDTO ghost;
 
    public Resolution add() {  
        ghost.setLastHaunted(new Date());
        ghost.setAbilities(new ArrayList<AbilityDTO>()); 
        ghost.setLvl(1);
        ghost.setExperience(1);

        if(ghost.getName().equals("Chuck Norris")){
            ghost.setLvl(6);
            ghost.setExperience(200);
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("event", "add");
        map.put("ghost", ghost);
        restTemplate.postForObject(URI, map, Map.class);
        return new RedirectResolution(this.getClass(), "ghosts");
    }
 
    public GhostDTO getGhost() {
        return ghost;
    }
 
    public void setGhost(GhostDTO ghost) {
        this.ghost = ghost;
    }
    
     public Resolution delete() {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("event", "delete");
        map.put("ghost", ghost);
        restTemplate.delete(URI + "/deleteGhost/" + ghost.getId().toString());
        return new RedirectResolution(this.getClass(), "ghosts");
    }
 
    public Resolution edit() {
        return new ForwardResolution("/jsp/ghostedit.jsp");
    }
 
    public Resolution save() {
        GhostDTO original = restTemplate.getForObject(URI+"/ghost?id="+ghost.getId(), GhostDTO.class); 
        AbilityType current = original.getAbilityType();
        AbilityType inserted = ghost.getAbilityType();
        if(current != inserted) {
            ghost.setAbilities(new ArrayList<AbilityDTO>());
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("event", "update");
        map.put("ghost", ghost);
        restTemplate.postForObject(URI, map, Map.class);
        return new RedirectResolution(this.getClass(), "ghosts");
    }
    
    public Resolution storno() {
        return new RedirectResolution(this.getClass(), "ghosts");
    }
    
    private Long house;
    
    public Long getSelectedHouse() {
        return house;
    }

    public void setSelectedHouse(Long selected) {
        this.house = selected;
    }
    
    
    private Long ability;
    
    public Long getSelectedAbility() {
        return ability;
    }

    public void setSelectedAbility(Long selected) {
        this.ability = selected;
    }
    
    public Resolution addAbilityToGhost() {
        if(ability != null) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("event", "addAbility");
            map.put("ghost", ghost);
            map.put("abilityId", ability);
            restTemplate.postForObject(URI, map, Map.class);  
        }
        return new RedirectResolution(this.getClass(), "all");
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save", "delete","setHouseToGhost", "addAbilityToGhost", "getAbilities"})
    public void loadGhostFromServer() {
        String ids = context.getRequest().getParameter("ghost.id");
        if (ids == null) {
            return;
        }
        GhostDTO ghst = restTemplate.getForObject(URI+"/ghost?id="+ids, GhostDTO.class);
        if (ghst == null) {
            return;
        }
        ghost=ghst;
    }
}
